package com.hksj.mqtt.config;

import cn.hutool.core.util.IdUtil;
import com.hksj.mqtt.callback.DefaultMqttCallBackAdapter;
import com.hksj.mqtt.client.IMqttClient;
import com.hksj.mqtt.callback.MqttCallBackAdapter;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
public class MqttConfig {
    @Autowired
    private ThreadPoolTaskExecutor executor;

    @Autowired
    private DefaultClientProperties defaultClientProperties;


    @Bean
    @ConditionalOnProperty(prefix = "hk.mqtt",name = "enable",havingValue = "true")
    public MqttCallBackAdapter defaultMqttCallBackAdapter(){
        return new DefaultMqttCallBackAdapter(executor);
    }

    @Bean
    @Primary
    @ConditionalOnProperty(prefix = "hk.mqtt",name = "enable",havingValue = "true")
    public IMqttClient iMqttClient() {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName(defaultClientProperties.getUsername());
        options.setPassword(defaultClientProperties.getPassword().toCharArray());
        options.setConnectionTimeout(defaultClientProperties.getTimeout());
        options.setKeepAliveInterval(defaultClientProperties.getKeepalive());
        options.setCleanSession(true);
        options.setAutomaticReconnect(true);
        return new IMqttClient(options, defaultClientProperties.getBrokerUrl(), defaultClientProperties.getClientIdPrefix() + IdUtil.fastSimpleUUID(), defaultMqttCallBackAdapter());
    }
}